package com.acxy.ants.core.plugin.entity;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @author MrShun
 * @version 1.0
 * @Date 2017-09-08
 */
public class CacheManager {

    public static ConcurrentMap<String, Cache> map = new ConcurrentHashMap<>();


    public static void put(String key, Cache cache){
        map.put(key, cache);
    }

    public static Object get(String key){
        Cache cache = map.get(key);
        if(cache == null) return null;
        return cache.getObj();
    }

    public static void remove(String key){
        map.remove(key);
    }

    public static void clear(String key){
        map.clear();
    }

    public static void refresh(String key){
        for(Map.Entry<String, Cache> entry: map.entrySet()){
            if(entry.getKey().startsWith(key)) remove(key);
        }
    }

    public static List<Map<String, Cache>> getAll(){
        List<Map<String, Cache>> result = new ArrayList<>();
        Set<Map.Entry<String, Cache>> entries = map.entrySet();
        for(Map.Entry<String, Cache> entry: entries){
            Map<String, Cache> map = new HashMap();
            map.put(entry.getKey(), entry.getValue());
            result.add(map);
        }
        return result;
    }

    public static boolean expire(String key){
        Cache cache = map.get(key);
        if(cache == null) return true;
        long sx = System.currentTimeMillis() - cache.getStartTime();
        return sx > cache.getTime() ? true: false;
    }
}
